'use client'
import TodoTitle from "./TodoTitle"
import AddTodo from "./AddTodo";
import TodoList from "./TodoList";
import Filter from "./Filter";
import {useRef, useState} from "react";
import {Todo} from "../types";
import {FilterEnum} from "../enums/FilterEnum"

// 模拟数据
const data: Todo[] = [
    {id: 1, text: "学习", completed: false},
    {id: 2, text: "吃饭", completed: false},
    {id: 3, text: "睡觉", completed: false},
    {id: 4, text: "写博客", completed: false},
    {id: 5, text: "打游戏", completed: false},
]



export default function TodoPage() {

    console.log("TodoPage重新渲染了")
    const [todos, setTodos] = useState<Todo[]>(data)
    const [filter, setFilter] = useState<FilterEnum>(FilterEnum.ALL)

    /**
     * id自增计数，也可以用Date.now()
     * useRef可以在重新渲染之间存储信息（普通对象存储的值每次渲染都会重置）
     */
    const idCount = useRef(data.length);

    /**
     *
     * @param text 添加的todo内容
     */
    function addTodo(text: string) {
        setTodos([...todos, {id: ++idCount.current, text, completed: false}])
        console.log("idCount.current:",idCount.current)
    }


    /**
     * 删除待办事项
     * @param id 删除的todo的id
     */
    function onDelete(id: number) {
        setTodos(todos.filter(todo => todo.id != id))
    }

    /**
     * 切换待办事项状态
     * @param id 切换的todo的id
     */
    function onToggle(id: number) {
        const newTodos = todos.map(todo => {
            if (todo.id == id) {
                todo.completed = !todo.completed
            }
            return todo
        })
        setTodos(newTodos)
    }

    /**
     *
     * @returns 根据filter筛选后的todo数组
     */
    function getFilterTodos(): Todo[] {
        switch (filter) {
            case FilterEnum.ALL:
                return (todos)
            case FilterEnum.UNCOMPLETED:
                return (todos.filter(todo => !todo.completed))
            case FilterEnum.COMPLETED:
                return (todos.filter(todo => todo.completed))
            default:
                return (todos)
        }

    }


    return (
        <div className="w-80 m-auto flex items-center flex-col">
            <TodoTitle></TodoTitle>
            <AddTodo addTodo={addTodo}/>
            <Filter setFilter={setFilter}></Filter>
            <TodoList
                todos={getFilterTodos()}
                onDelete={onDelete}
                onToggle={onToggle}
            ></TodoList>
        </div>
    )
}

